frappe.provide("zelin_shoe_biz");
frappe.provide("zelin_shoe_biz.utils");

$.extend(zelin_shoe_biz.utils, {
    preview_file: function (frm) {
		let $preview = "";
		let file_extension = frm.doc.drawing_file.split('.').pop().toLowerCase();

		if (frappe.utils.is_image_file(frm.doc.drawing_file)) {
			$preview = $(`<div class="img_preview" style="display: flex;justify-content: center;">
				<img
					class="img-responsive shortcut-widget-box"
					src="${frappe.utils.escape_html(frm.doc.drawing_file)}"
					style="max-height: 200px; width: auto;"  // 关键修改：限制高度为 200px，宽度自适应
					onerror="${frm.toggle_display("preview", false)}"
				/>
			</div>`);
		} else if (file_extension === "pdf") {
			$preview = $(`<div class="img_preview">
				<object style="background:#323639;" width="100%">
					<embed
						style="background:#323639;"
						width="100%"
                        height="200"
						src="${frappe.utils.escape_html(frm.doc.drawing_file)}" type="application/pdf"
					>
				</object>
			</div>`);
		} 
		if ($preview && !frm.doc.__islocal) {			            
			frm.get_field("preview_html").$wrapper.html($preview);
		}
	},
	
	change_grid_col_label: function(frm, table_field="items") {
		if (frm.doc.size_range) {
			frappe.db.get_doc('Size Range', frm.doc.size_range).then(size_range_doc => {
				let grid = frm.get_field(table_field).grid;
				for (let j = 1; j <= 20; j++) {
					let size_field_name = `size_${j}`;
					let qty_field_name = `qty_${j}`;
					let new_label = size_range_doc[size_field_name] || ""
			
					// Update grid column header
					let grid_col_field = grid.fields_map[qty_field_name];
					if (grid_col_field) {
						grid_col_field.label = new_label;
					}
					const user_defined_col = grid.user_defined_columns.find(col => col.fieldname === qty_field_name);
					if (user_defined_col) {
						user_defined_col.label = new_label;
					}        
				}        			
			    grid.setup_visible_columns();       
			    grid.header_row.wrapper.remove();
			    delete grid.header_row;
			    grid.make_head();
			    grid.reset_grid();            
			})
		}
	}
})